package edu.neumont.MillerK.AndroidServlets;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;

import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;

import edu.neumont.MillerK.POJOs.Security;
import edu.neumont.MillerK.Web.DBQueries.*;
import edu.neumont.MillerK.Web.Entities.User;

/**
 * Servlet implementation class AndroidCommandServlet
 */
@WebServlet("/AndroidCommands")
public class AndroidCommandServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Resource
	UserTransaction utx;
	
	@PersistenceUnit
	EntityManagerFactory emf;
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("Android Command Servlet HERE!!!!!!");
		DBQueries dbQueries = new DBQueries(emf, utx);
		Security security = new Security();
		String emailUsername = request.getParameter("emailUsername");
		String password = request.getParameter("password");
		String features = request.getParameter("features");
		User user = dbQueries.getUser(emailUsername);
		if(user != null){
			try {
				if(user.getPassword().equals(security.SHAHash(password + user.getSalt()))){
					dbQueries.updateUserFeatures(user, features);
					System.out.println("[AndroidCommandServlet] commands: " + user.getCommands());
					response.setHeader("commands", user.getCommands());
					dbQueries.updateUserCommands(user, new char[]{'2','2','2','2','2','2'});
				}
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
		}
	}
}